<template>
  <div class="change-password-container">
    <div class="change-password-card">
      <div class="header">
        <h2>修改密码</h2>
        <button class="close-btn" @click="goBack">×</button>
      </div>

      <form @submit.prevent="handleSubmit" class="password-form">
        <div class="form-group">
          <label for="oldPassword">旧密码</label>
          <div class="input-wrapper">
            <input
              id="oldPassword"
              v-model="formData.oldPassword"
              :type="showOldPassword ? 'text' : 'password'"
              placeholder="请输入旧密码"
              required
            />
            <button
              type="button"
              class="toggle-password"
              @click="showOldPassword = !showOldPassword"
            >
              {{ showOldPassword ? '👁️' : '👁️‍🗨️' }}
            </button>
          </div>
        </div>

        <div class="form-group">
          <label for="newPassword">新密码</label>
          <div class="input-wrapper">
            <input
              id="newPassword"
              v-model="formData.newPassword"
              :type="showNewPassword ? 'text' : 'password'"
              placeholder="请输入新密码（至少6位）"
              required
              minlength="6"
            />
            <button
              type="button"
              class="toggle-password"
              @click="showNewPassword = !showNewPassword"
            >
              {{ showNewPassword ? '👁️' : '👁️‍🗨️' }}
            </button>
          </div>
          <div class="password-strength">
            <div class="strength-bar" :class="passwordStrength"></div>
            <span class="strength-text">{{ passwordStrengthText }}</span>
          </div>
        </div>

        <div class="form-group">
          <label for="confirmPassword">确认新密码</label>
          <div class="input-wrapper">
            <input
              id="confirmPassword"
              v-model="formData.confirmPassword"
              :type="showConfirmPassword ? 'text' : 'password'"
              placeholder="请再次输入新密码"
              required
            />
            <button
              type="button"
              class="toggle-password"
              @click="showConfirmPassword = !showConfirmPassword"
            >
              {{ showConfirmPassword ? '👁️' : '👁️‍🗨️' }}
            </button>
          </div>
          <div v-if="formData.confirmPassword && !passwordsMatch" class="error-message">
            两次输入的密码不一致
          </div>
        </div>

        <div v-if="errorMessage" class="alert alert-error">
          {{ errorMessage }}
        </div>

        <div v-if="successMessage" class="alert alert-success">
          {{ successMessage }}
        </div>

        <div class="form-actions">
          <button type="button" class="btn btn-cancel" @click="goBack">取消</button>
          <button
            type="submit"
            class="btn btn-submit"
            :disabled="!isFormValid || isSubmitting"
          >
            {{ isSubmitting ? '提交中...' : '确认修改' }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { updatePassword } from '@/api'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

// 表单数据
const formData = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 显示/隐藏密码
const showOldPassword = ref(false)
const showNewPassword = ref(false)
const showConfirmPassword = ref(false)

// 提交状态
const isSubmitting = ref(false)
const errorMessage = ref('')
const successMessage = ref('')

// 密码强度计算
const passwordStrength = computed(() => {
  const pwd = formData.value.newPassword
  if (!pwd) return ''
  if (pwd.length < 6) return 'weak'
  
  let strength = 0
  if (pwd.length >= 8) strength++
  if (/[a-z]/.test(pwd) && /[A-Z]/.test(pwd)) strength++
  if (/\d/.test(pwd)) strength++
  if (/[^a-zA-Z0-9]/.test(pwd)) strength++
  
  if (strength <= 1) return 'weak'
  if (strength <= 2) return 'medium'
  return 'strong'
})

const passwordStrengthText = computed(() => {
  const strength = passwordStrength.value
  if (!formData.value.newPassword) return ''
  if (strength === 'weak') return '密码强度：弱'
  if (strength === 'medium') return '密码强度：中'
  if (strength === 'strong') return '密码强度：强'
  return ''
})

// 密码是否匹配
const passwordsMatch = computed(() => {
  return formData.value.newPassword === formData.value.confirmPassword
})

// 表单是否有效
const isFormValid = computed(() => {
  return (
    formData.value.oldPassword.length >= 6 &&
    formData.value.newPassword.length >= 6 &&
    formData.value.confirmPassword.length >= 6 &&
    passwordsMatch.value
  )
})

// 提交表单
const handleSubmit = async () => {
  if (!isFormValid.value) return

  // 检查新旧密码是否相同
  if (formData.value.oldPassword === formData.value.newPassword) {
    errorMessage.value = '新密码不能与旧密码相同'
    return
  }

  isSubmitting.value = true
  errorMessage.value = ''
  successMessage.value = ''

  try {
    const userId = userStore.userId
    if (!userId) {
      throw new Error('用户未登录')
    }

    await updatePassword(userId, {
      oldPassword: formData.value.oldPassword,
      newPassword: formData.value.newPassword
    })

    successMessage.value = '密码修改成功！3秒后将跳转到登录页...'
    
    // 3秒后清除登录状态并跳转到登录页
    setTimeout(() => {
      userStore.clearAuth()
      router.push('/user-login')
    }, 3000)
  } catch (error) {
    console.error('修改密码失败:', error)
    errorMessage.value = error.response?.data?.message || error.message || '修改密码失败，请检查旧密码是否正确'
  } finally {
    isSubmitting.value = false
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}
</script>

<style scoped>
@import '@/CSS/ChangePassword.css';
</style>

